package com.yxkj.railservicer.pager;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.activity.CompleteActivity;
import com.yxkj.railservicer.adapter.CancelAdapter;
import com.yxkj.railservicer.adapter.CompleteAdapter;
import com.yxkj.railservicer.bean.CancelBean;
import com.yxkj.railservicer.bean.CompleteBean;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.SPUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by sunyu on 2017/4/4.
 */

public class Cancelpager extends CompleteBasePager implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    private View view;
    private RecyclerView can_content_view;
    private CancelAdapter adapter;
    private List<CancelBean> list;
    private OkHttpClient client;
    private CanRefreshLayout refresh;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;
    private String token;

    private JSONUtil jsonUtil;

    public Cancelpager(Activity activity) {
        super(activity);
    }

    @Override
    public void initData() {
        super.initData();
        if (view == null) {
            view = View.inflate(activity, R.layout.pager_base, null);

            can_content_view = (RecyclerView) view.findViewById(R.id.can_content_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
            can_content_view.setLayoutManager(layoutManager);

            jsonUtil = new JSONUtil();

            client = new OkHttpClient();


            can_refresh_header = (ClassicRefreshView) view.findViewById(R.id.can_refresh_header);
            can_refresh_footer = (ClassicRefreshView) view.findViewById(R.id.can_refresh_footer);

            can_refresh_header.setRefreshingStr("正在刷新");
            can_refresh_header.setPullStr("下拉刷新");
            can_refresh_header.setReleaseStr("松手刷新");
            can_refresh_header.setCompleteStr("刷新完成");

            can_refresh_footer.setRefreshingStr("正在加载");
            can_refresh_footer.setPullStr("上拉加载");
            can_refresh_footer.setReleaseStr("松手加载更多");
            can_refresh_footer.setCompleteStr("加载完成");

            refresh = (CanRefreshLayout) view.findViewById(R.id.refresh);
            //下拉刷新
            refresh.setOnRefreshListener(this);
            //上拉加载
            refresh.setOnLoadMoreListener(this);
            //刷新样式
            refresh.setStyle(0, 0);

            list = new ArrayList<>();

            adapter = new CancelAdapter(list, activity);

            can_content_view.setAdapter(adapter);

            fl_basepager.addView(view);
        }
        onRefresh();
    }

    private String total;

    private void getInfo() {
//        for (int i = 0; i < 4; i++) {
//            list.add(new CancelBean("2017-3-20 11:15", "订单号111", "18:11", "","肯德基餐厅","长沙","二层检票口B","不想吃了"));
//        }

        token = SPUtil.getString(activity, "token");

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.queryCancelOrdersToday_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        total = data.size() + "";
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject o = data.getJSONObject(i);
                            String updateDate = o.getString("updateDate");
                            String orderNo = o.getString("orderNo");
                            String latestServiceTime = o.getString("latestServiceTime").substring(11, 16);
                            String merchantLogoUrl = o.getString("merchantLogoUrl");
                            String merchantName = o.getString("merchantName");
                            String fromAddress = o.getString("fromAddress");
                            String deliverAddress = o.getString("deliverAddress");
                            String cancelReason = o.getString("cancelReason");

                            list.add(new CancelBean(updateDate, orderNo, latestServiceTime, merchantLogoUrl, merchantName, fromAddress, deliverAddress, cancelReason));
                        }
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((CompleteActivity) activity).getCount(Cancelpager.this, total);
                        adapter.notifyDataSetChanged();
                    }
                });

                Log.e("TAG", "查询联网成功" + jsonData);
            }
        });
    }


    private int pages;

    @Override
    public void onRefresh() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages = 0;
                list.clear();
                getInfo();
                refresh.refreshComplete();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages++;
                list.clear();
                getInfo();
                can_refresh_footer.setCompleteStr("");
                refresh.loadMoreComplete();
            }
        }, 1000);
    }

    private void toast(final String string) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(activity, string, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
